package le.cn.aio.server;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, AsyncTimeServerHandler> {

    /**
     * 当IO完成时触发该方法，该方法的第一个参数代表IO操作返回的对象，第二个参数代表发起IO操作时传入的附加参数。
     * @param result
     * @param attachment
     */
    @Override
    public void completed(AsynchronousSocketChannel result, AsyncTimeServerHandler attachment) {
        attachment.getAsynchronousServerSocketChannel().accept(attachment,this);
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        System.out.println("accep handler");
        result.read(byteBuffer,byteBuffer,new ReadCompletionHandler(result));
    }
    /**
     * 当IO失败时触发该方法，第一个参数代表IO操作失败引发的异常或错误。
     * @param exc
     * @param attachment
     */
    @Override
    public void failed(Throwable exc, AsyncTimeServerHandler attachment) {
        exc.printStackTrace();;
        // 递减锁存器的计数，如果计数到达零，则释放所有等待的线程
        attachment.getLatch().countDown();
    }
}
